<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/3/19
 * Time: 上午10:47
 */

namespace Biz\module\Classes;

use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\model\trade\OrderMatching;
use Biz\model\trade\OrderRefund as mOrderRefund;
use Biz\module\Classes\OrderRefund as clsOrderRefund;
use Biz\module\Classes\traits\AmountStruct;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\service\activity\GroupBuy as sGroupBuy;
use Biz\service\ShopInfo as sShopInfo;
use Biz\service\trade\Logistics as sLogistics;
use Biz\module\Packages\CustomerService\SmallEnergy as csSmallEnergy;
use Biz\module\Classes\Order as clsOrder;
use Biz\module\Classes\OrderInfo as clsOrderInfo;
use Doraemon\tools\HhzClient;
use Biz\model\trade\ShopCourier as mShopCourier;
use Biz\service\activity\PinTuan as sPinTuan;
use Biz\service\Goods as sGoods;
use Biz\service\redPacket\RedPacketsLog as sRedPacketsLog;
use Biz\model\trade\OrderPackage as mOrderPackage;

class OrderDetail implements ActivityInfo
{
    use AmountStruct;
    public function info($orderNo, $uid = 0)
    {
        $data = [];

        $from = HhzClient::getClientType();


        //根据UID和订单号查询订单信息
        $order = mOrder::getOrderInfo($orderNo);


        if ($order === false) {
            throw new \Exception('抱歉，该订单不存在');
        }

        if ($uid !== 0) {
            if ($uid != $order['uid']) {
                throw new \Exception('抱歉，该订单不存在');
            }
        }

        //针对APP端，部分发货状态要转成已发货
        if($order['status'] == mOrder::STATUS_SEND_PART_OUT){
            $order['v_status'] = mOrder::STATUS_SEND_OUT;
        }



        $data = [
            "order_no" => $order['order_no'],
            "message" => $order['message'],
            "status" => $order['v_status'],
            'is_package_delivery'=>(int)$order['is_package_delivery'],
            'real_status'=>$order['status']
        ];


        //如果是节选小程序，同时主单为一次性自提，则返回物流公司ID
        if($from == HhzClient::APPTYPE_PARAGRAPH_MINIPROGRAM){
            $orderPackage = mOrderPackage::getFirstPackageInfo($orderNo);

            $courierInfo = mShopCourier::getCourier(['courier_id'],['courier_name'=>$orderPackage['express_company']]);

            $data['courier_id'] = isset($courierInfo['courier_id'])?$courierInfo['courier_id']:0;
        }

        if(in_array($order['status'] , [mOrder::STATUS_WAIT_SEND,mOrder::STATUS_SEND_PART_OUT,mOrder::STATUS_SEND_OUT,mOrder::STATUS_SUCCESS])){
            //期望配送的信息
            $orderMatching = OrderMatching::getInfo($orderNo);
            $data['consignee_time'] = isset($orderMatching[0]['consignee_time']) ?$orderMatching[0]['consignee_time']:'';
        }



        //格式化输出收货人信息
        $data['accept_info'] = [
            'accept_name' => $order['consignee_name'],
            'mobile' => $order['consignee_phone'],
            'province' => $order['consignee_province'],
            'city' => $order['consignee_city'],
            'address' => $order['consignee_address'],
        ];

        $shopInfo = sShopInfo::getShopInfo($order['shop_id'], ['user']);
        $smallEnergyInfo = csSmallEnergy::getSmallEnergyInfoByShopId($order['shop_id'], ['pre_sale_reception_group_id']);

        //订单所属商家信息
        $data['shop_info'] = [
            'shop_id' => $order['shop_id'],
            'shop_name' => $shopInfo['shop_name'],
            'imgurl' => $shopInfo['shop_imgurl_small'],
            'cover_img' => $shopInfo['shop_imgurl_small'],
            'shop_icon' => $shopInfo['shop_imgurl_small'],
            'status' => $shopInfo['status'],
            'se_group_id' => $smallEnergyInfo['pre_sale_reception_group_id']? : csSmallEnergy::GROUP_ID,
            'small_energy' => [
                'pre_sale_reception_group_id' => $smallEnergyInfo['pre_sale_reception_group_id'] ?: csSmallEnergy::GROUP_ID,
            ]
        ];

        //获取sku信息
        $skuList = mOrderGoods::getOrderGoodsList($orderNo);

        if (empty($skuList)) {
            return $data;
        }

        //获取退款单号
        $refundOrderNos = array_column($skuList, 'refund_order_no','sku_id');

        $refundInfoList = OrderRefundInfo::getRefundStatusInfo($order['status'],$refundOrderNos);

        foreach ($skuList as $orderSku) {

            if ($from == HhzClient::APPTYPE_TUAN_MINIPROGRAM && !isset($promoId)) {
                if ($orderSku['promo_type'] == self::ACTIVITY_TYPE_TUAN) {
                    $promoId = $orderSku['promo_id'];
                }
            }


            //refundInfo初始化并赋值
            $refundInfo = null;
            if (key_exists($order['status'], mOrder::$paiedStatusList) || ($order['cancel_type'] == 0 && $order['status'] == mOrder::STATUS_CLOSE)) {
                $refundInfo = !empty($refundInfoList[$orderSku['sku_id']]) ? $refundInfoList[$orderSku['sku_id']] : null;
            }
//            $refundInfo = Order::zyjtVersion() ? null : $refundInfo;

            $data['sku_list'][] = [

                'sku_id' => $orderSku['sku_id'],
                'goods_id' => $orderSku['goods_id'],
                'title' => $orderSku['title'],
                'cover_img' => $orderSku['cover_img_thumb_url'],
                'sku_desc' => $orderSku['sku_desc'],
                'sell_price' => $orderSku['sell_price'],
                'buy_price' => $orderSku['buy_price'],
                'buy_num' => $orderSku['buy_num'],
                'refund_info' => $refundInfo,
                'promo_id' => $orderSku['promo_id'],
                'promo_type' => $orderSku['promo_type'],
                'order_no' => $orderSku['order_no'],
                'reserve_receipt_time'=>strtotime($orderSku['reserve_receipt_time'])>0?$orderSku['reserve_receipt_time']:''
            ];

            //是否参与活动
            if( $orderSku['promo_type'] > 0 ){
                $activitys[$orderSku['promo_type']][] = $orderSku['order_no'];
            }

        }

        if(isset($activitys)){
            $activity = self::getActivity($activitys, $data['sku_list']);
            $goodsList = array_column($skuList, 'goods_id');
            $goodsList = sGoods::goodsBrands($goodsList);
        }

        if(isset($activity)  && !empty($activity)){
            foreach($activity as $_ak=>&$_av) {
                if (isset($_av[$orderNo])) {
                    $data[$_ak] = $_av[$orderNo];
                    //分享
                    if ($_ak == 'team_join_info') {
                        $share_info[$_av[$orderNo]['goods_id']] = [
                            'team_join_id'=>$_av[$order['order_no']]['team_join_id'],
                            'group_buy_price'=>$_av[$order['order_no']]['group_buy_price']
                        ];
                    }
                    if(isset($share_info)) {
                        $goodsLists = array_column($goodsList, NUll, 'goods_id');
                        $goodsShare = sGoods::goodsPintuanShare([$goodsLists[$data['team_join_info']['goods_id']]], $share_info[$data['team_join_info']['goods_id']]);
                        if (isset($goodsShare[$data['team_join_info']['goods_id']])) {
                            $data['share_info'] = $goodsShare[$data['team_join_info']['goods_id']];
                        }
                    }
                }
                if($_ak == $order['order_no']){
                    $data['sku_list'][0] = array_merge($data['sku_list'][0], $_av);
                }
            }
        }


        //组装订单信息
        $data['summary'] = [
            "subtotal"=>$order['goods_amount'],
            "pay_amount" => $order['pay_amount'],
            "shipping_amount" => $order['shipping_amount'],
        ];

        //组装积分信息
        $data['integral']['discount'] = $order['integral_amount'];

        $data['coupon']['discount'] = $order['coupon_amount'];
        $data['coupon']['s_discount'] = $order['s_coupon_amount'];
        $data['activity']['allowance'] = $order['activity_allowance'];

        //套餐优惠金额
        if($order['meal_id'] > 0){
            $data['meal'] = [
                'meal_id'=>$order['meal_id'],
                'detract_amount'=>$order['meal_amount']
            ];
        }

        if (in_array($order['status'], [mOrder::STATUS_SUCCESS, mOrder::STATUS_SEND_OUT,mOrder::STATUS_SEND_PART_OUT])) {
            //物流信息
            $data['delivery_tracking'] = clsOrderInfo::getOrderLastOneLogistics($orderNo,$order);
        }


        //组装时间信息
        $data['time_info']['add_time'] = $order['addtime'];
        $data['time_info']['now_time'] = date('Y-m-d H:i:s');
        $data['time_info']['pay_time'] = $order['pay_time'];


        if ($order['status'] == mOrder::STATUS_NORMAL && isset($order['paystop_time'])) {
            $data['time_info']['paystop_time'] = $order['paystop_time'];
        } elseif ($order['status'] == mOrder::STATUS_SEND_OUT && isset($order['autoconfirm_time'])) {

            //如果是有在进行中的退款申请，那么在详情页就不显示自动确认收货的倒计时
            $clsOrderRefund = new clsOrderRefund();
            $refundingStatus = $clsOrderRefund->checkOrderHasRefunding([$orderNo => mOrder::STATUS_SEND_OUT], 'userReceipt');

            if ($refundingStatus != clsOrderRefund::REFUNDING_YES && $refundingStatus != clsOrderRefund::REFUNDING_RIGHTS_IN) {
                $data['time_info']['autoconfirm_time'] = $order['autoconfirm_time'];
                $data['time_info']['maxprolong_time'] = $order['maxprolong_time'];
            }

        }


        //判断时间是否正常
        $data['time_info'] = array_filter(array_map(function ($v) {
            return strtotime($v);
        },$data['time_info']), function ($v) {
            if ($v > 0) {
                return true;
            }
            return false;
        });

        //团购相关展示
        //只有来源是团购的APP才计算
        if (isset($promoId)) {
            $groupbuy = sGroupBuy::isGroupSuccess([$promoId]);

            $data['groupbuy'] = isset($groupbuy[$promoId])?$groupbuy[$promoId]:[];
            $data['groupbuy']['group_buy_id'] = $promoId;
        }


        //amount_struct组装
        $renderAmount = [
            'shipping_fee'=>$order['shipping_fee'],
            'shipping_amount'=>$order['shipping_amount'],
            'shipping_discount'=>$order['shipping_fee']-$order['shipping_amount'],
            'integral_amount'=>$order['integral_amount'],
            'coupon_amount'=>$order['coupon_amount'],
            's_coupon_amount'=>$order['s_coupon_amount'],
            'activity_allowance'=>$order['activity_allowance'],
            'meal_amount'=>$order['meal_amount'],
        ];
        //是否使用红包
        if(!empty(sRedPacketsLog::getInfo($orderNo))) {
            $renderAmount['red_packet'] = sRedPacketsLog::getInfo($orderNo);
        }
        $renderAmount['pay_amount'] = $order['pay_amount'];
        $data['amount_struct'] = self::renderAmountStruct($renderAmount);

        return $data;
    }

    private static function getActivity($activity, $skuList){
        $data = [];
        foreach(ActivityInfo::ACTIVITY_TYPES_MAPS as $_k=>$_v) {
            switch ($_k) {
                case ActivityInfo::ACTIVITY_TYPE_PINTUAN;
                    $data = sPinTuan::getSkuOrder($activity[ActivityInfo::ACTIVITY_TYPE_PINTUAN], $skuList);
                    break;
            }
        }
        return $data;
    }


}